package com.woniu.controller;

import com.woniu.domain.Menu;
import com.woniu.domain.ResponseEntity;
import com.woniu.domain.User;
import com.woniu.service.MenuService;
import com.woniu.service.UserLoginService;
import com.woniu.token.JWTUtil;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;
/**
 * @author: 刘家元  <br/>
 * Date: 2021/6/8:12:20  <br/>
 * Description:登录控制器
 */

@RestController
public class LoginController {
    @Autowired
    private UserLoginService userLoginService;
    @Autowired(required = false)
    RedisTemplate redisTemplate;

    @RequestMapping("/login")
    public ResponseEntity login(String account, String password){
        //根据注册的时候 或者修改manager里面的加密方式来, 只要一样即可
        SimpleHash md5 = new SimpleHash("MD5", password, account);
        //获取加密后的密码d
        String newPassword = md5.toHex();
        System.out.println(newPassword);
        User user = userLoginService.userGetByaccount(account);
        if(user.getPassword().equals(newPassword)){
            user.setToken(JWTUtil.sign(account, newPassword));
            System.out.println(user);
            //往redis中存一份 同时设置一个过期时间
            redisTemplate.opsForValue().set(JWTUtil.sign(account, newPassword),user);
            //对某个key设置其过期时间  1800s后过期 但是请取消5分钟过期的jwt判断
            redisTemplate.expire(user.getToken(),1800, TimeUnit.SECONDS);
            System.out.println(redisTemplate.opsForValue().get(JWTUtil.sign(account, newPassword)));
            return new ResponseEntity(200, "登录成功",user);
        }else{
            throw new UnauthorizedException();
        }
    }
}
